package com.headingdata.atm;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class ATM {

    private ArrayList<Account> accounts = new ArrayList<>();
    private Scanner scanner = new Scanner(System.in);

    public void start(){
        while (true) {
            System.out.println("===欢迎进入===");
            System.out.println("1.用户登录");
            System.out.println("2.用户开户");
            System.out.println("请选择：");
            int command = scanner.nextInt();
            switch (command){
                case 1:
                    //用户登录
                    break;
                case 2:
                    createAccount();
                    //用户开户
                    break;
                default:
                    System.out.println("您输入的选择不存在，请重新选择！");
                    break;
            }
        }
    }

    public void createAccount(){
        Account account = new Account();

        System.out.println("==欢迎进入开户系统==");
        System.out.println("请输入姓名：");
        String userName = scanner.next();
        account.setUserName(userName);

        while (true) {
            System.out.println("请输入性别：");
            char sex = scanner.next().charAt(0);
            if(sex == '男' || sex == '女'){
                account.setSex(sex);
                break;
            }else{
                System.out.println("您输入的性别不正确，请输入”男“或”女“");
            }

        }

        while (true) {
            System.out.println("请输入密码：");
            String password = scanner.next();
            System.out.println("请再次输入密码：");
            String password1 = scanner.next();
            if(!password1.equals(password)){
                System.out.println("您两次输入的密码不一致，请重新输入！");
            }else {
                break;
            }
        }

        System.out.println("请输入您的账户余额：");
        double balance = scanner.nextDouble();
        account.setBalance(balance);

        System.out.println("请输入转账限额：");
        double limit = scanner.nextDouble();
        account.setBalance(limit);

        String cardId = generateCardId();
        account.setCardId(cardId);

        accounts.add(account);
        System.out.println("恭喜您，" + account.getUserName() + "开户成功，您的卡号是" + account.getCardId());

    }

    public String generateCardId(){
        Random r = new Random();
        String cardId = "";
        while (true) {
            for (int i = 0; i < 8; i++) {
                cardId += r.nextInt(10);
            }
            if(!judgeExistCardId(cardId)){
                break;
            }
        }
        return cardId;
    }

    public boolean judgeExistCardId(String cardId){
        for (int i = 0; i < accounts.size(); i++) {
            if(accounts.get(i).equals(cardId)){
                return true;
            }
        }
        return false;
    }

}
